#coding:utf-8

from flask import request
from flask import session
from flask import redirect
import models.note as note
from flask import render_template
import models.material as material
import models.biding as  biding
import libs.weixinApi.mes_redis as message_interface
import libs.util.json_enable_chinese as my_encode
import libs.weixinApi.gen_message_link as get_message_link

#@TODO 获取material信息
def send_note_route(app):
    @app.route('/note/set-material', methods=['GET'])
    def set_material_for_note():
        material_id = request.args.get("id")
        try:
            initial_id = material.get_latest_material(material_id)
            if(initial_id):
                session['material_sub_id'] = material_id
                session['initial_id'] = initial_id
                return redirect('/note/send')
            else:
                return 500
        except:
            return 500

    @app.route('/note/send', methods=['GET','POST'])
    def note_send():
            session['stu_id'] = '121270026'
            session['name'] = u'aesop'
            session['material_id'] = 'deee34324235'
            if(session['material_id']):
                if(request.method == 'POST'):
                    arg = {
                        "people_list":request.form["people_list"],
                        "stu_id":session['stu_id'],
                        "name":session['name'],
                        'material_sub_id':session['material_sub_id'],
                        'note_sort':request.form['note_type'],
                        'title':request.form['title']
                    }

                    result = note.new_note(arg)

                    url = get_message_link.gen_message_link(str(result))
                    body = eval(request.form["people_list"])
                    openid_list = [ (x,biding.find_openid(x)) for x in body]
                    for openid_stu in openid_list:
                        dic = {
                            "note_id": str(result),
                            "touser":openid_stu[1]['openid'],
                            "title":request.form['title'],
                            "url":url,
                            "stu_id":openid_stu[0]
                        }
                        message_interface.send_message(my_encode.json_aesop.encode(dic))
                    return '0'
                else:
                    return render_template("pub-notification/send-msg.html",user = session)
            else:
                return u"尚未选择素材"




    @app.route('/note/history', methods=['GET'])
    def note_history():
        pre_content = note.get_note_list(session['stu_id'])
        content = {}
        content["note_list"] = []
        for item in pre_content:
            note_material_sub_id = material.get_latest_material(item["note_material_sub_id"])
            note_material = material.get_content_material_by_id(note_material_sub_id)
            single_content = {
                "note_id": str(item['_id']),
                "publish_person": item['publish_person'],
                "publish_time":item['publish_time'],
                "title":item["title"],
                "material_title":note_material["title"],
                "content":note_material["content"]

            }
            if(item['note_sort'] == 0):
                single_content['note_sort'] = u"通知"
            else:
                single_content['note_sort'] = u'花边'
            if(item['is_passed'] == 0):
                single_content['is_passed'] = u'未审核'
                single_content['is_pushed'] = u'-'
                single_content['read_person_count'] = u'-'
                single_content['good_count'] = u'-'
                single_content['received_count'] = u'-'
                single_content['should_count'] = u'-'
            elif(item['is_passed'] == -1):
                single_content['is_passed'] = u'未通过审核'
                single_content['is_pushed'] = u'-'
                single_content['read_person_count'] = u'-'
                single_content['good_count'] = u'-'
                single_content['received_count'] = u'-'
                single_content['should_count'] = u'-'
            else:
                single_content['is_passed'] = u'审核通过'
                single_content['is_pushed'] = u'是'
                single_content = dict (__note_statics(item['receiver']).items() + single_content.items())
            content['note_list'].append(single_content)
        content['note_list'].reverse()
        return render_template('pub-notification/send-history.html',content = content,user = session)


def __note_statics(receivers):
            single_content = {
                'read_person_count':0,
                'good_count':u'-',
                'received_count':0,
                'should_count':0
            }
            for item in receivers:
                if(item['is_read']):
                    single_content['read_person_count'] = u'-'
                if(item['is_send']):
                    single_content['received_count'] = u'-'
                single_content['should_count'] += 1

            return single_content

